"""扫描问题Service"""
from typing import List, Optional, Dict, Any
from datetime import datetime
from sqlalchemy.orm import Session
from app.repositories.issue_repository import IssueRepository
from app.repositories.field_config_repository import FieldConfigRepository
from app.models.issue import Issue
from app.models.scan_issue_extension import ScanIssueExtension


class IssueService:
    """扫描问题业务逻辑层"""

    def __init__(self, db: Session):
        self.repository = IssueRepository(db)
        self.field_config_repo = FieldConfigRepository(db)
        self.db = db

    def get_by_record_id(
        self,
        record_id: int,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None,
        order_by: Optional[str] = None,
    ) -> List[Issue]:
        """根据扫描记录ID获取问题列表"""
        return self.repository.get_by_record_id(
            record_id=record_id,
            skip=skip,
            limit=limit,
            filters=filters,
            order_by=order_by,
        )

    def get_by_id(self, issue_id: int) -> Optional[Issue]:
        """根据ID获取问题详情（包含扩展字段）"""
        issue = self.repository.get(issue_id)
        if issue:
            # 获取扩展字段数据
            extensions = self.repository.get_extensions(issue_id)
            # 将扩展字段添加到issue对象（通过动态属性）
            issue.extension_data = extensions
        return issue

    def get_extensions(self, issue_id: int) -> Dict[str, Any]:
        """获取问题的扩展字段数据"""
        return self.repository.get_extensions(issue_id)

    def confirm_issue(
        self,
        issue_id: int,
        confirm_type: str,
        confirmed_by: str,
        confirm_comment: Optional[str] = None,
    ) -> Optional[Issue]:
        """确认问题"""
        issue = self.repository.get(issue_id)
        if not issue:
            return None

        # 更新问题确认信息
        issue.confirm_status = "confirmed"
        issue.confirm_type = confirm_type
        issue.confirmed_by = confirmed_by
        issue.confirmed_at = datetime.now()
        if confirm_comment:
            issue.confirm_comment = confirm_comment

        self.db.commit()
        self.db.refresh(issue)

        # TODO: 创建确认历史记录（Phase 2后续实现）

        return issue

    def batch_confirm(
        self,
        issue_ids: List[int],
        confirm_type: str,
        confirmed_by: str,
        confirm_comment: Optional[str] = None,
    ) -> List[Issue]:
        """批量确认问题"""
        confirmed_issues = []
        for issue_id in issue_ids:
            issue = self.confirm_issue(
                issue_id=issue_id,
                confirm_type=confirm_type,
                confirmed_by=confirmed_by,
                confirm_comment=confirm_comment,
            )
            if issue:
                confirmed_issues.append(issue)
        return confirmed_issues

    def count_by_record_id(self, record_id: int) -> int:
        """统计扫描记录的问题数"""
        return self.repository.count_by_record_id(record_id)

    def count_by_level(self, record_id: int, level: str) -> int:
        """统计指定级别的问题数"""
        return self.repository.count_by_level(record_id, level)

